import asyncio
from celery import shared_task
from .models import WorkflowExecution

@shared_task
def execute_workflow(execution_id):
    execution = WorkflowExecution.objects.get(id=execution_id)
    execution.status = 'running'
    execution.started_at = timezone.now()
    execution.save()
    
    try:
        executor = WorkflowExecutor(execution.workflow.id)
        executor.validate_workflow()
        
        # 异步执行
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        result = loop.run_until_complete(executor.execute(execution.input_data))
        
        execution.output_data = result
        execution.status = 'completed'
    except Exception as e:
        execution.output_data = {'error': str(e)}
        execution.status = 'failed'
    finally:
        execution.completed_at = timezone.now()
        execution.save()